<template>
  <div class="patient-dashboard">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部导航 -->
      <div class="top-nav">
        <div class="profile-section">
          <div class="user-avatar">
            <img src="@/assets/病人.png" alt="Patient" />
          </div>
          <h2 class="page-title">患者档案</h2>
        </div>
        <div class="nav-actions">
          <el-button class="nav-button" circle>
            <el-icon><User /></el-icon>
          </el-button>
          <el-button class="nav-button" circle>
            <el-icon><Bell /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 患者信息卡片 -->
      <div class="patient-info-card">
        <div class="card-content">
          <div class="patient-header">
            <h3>患者信息</h3>
            <div class="action-buttons">
              <el-button type="danger" size="small" @click="showPatientList">患者列表</el-button>
              <el-button type="primary" size="small" @click="handleAddPatient">添加患者</el-button>
            </div>
          </div>
          
          <div class="patient-details">
            <!-- 患者头像区域 -->
            <div class="patient-avatar-section">
              <div class="avatar-container">
                <img :src="currentPatient.avatar || '/src/assets/病人.png'" alt="Patient Avatar" />
              </div>
            </div>
            
                <!-- 患者信息区域 -->
    <div class="patient-info-section" v-loading="loading">
      <div class="info-group">
        <div class="info-header">
          <h4>基本信息</h4>
          <el-button 
            type="primary" 
            size="small" 
            :icon="Edit" 
            @click="handleEditPatient"
            v-if="currentPatient.id"
          >
            编辑信息
          </el-button>
        </div>
                <div class="basic-info">
                  <p class="info-text"><strong>姓名：</strong>{{ currentPatient.name }}</p>
                  <p class="info-text"><strong>性别：</strong>{{ currentPatient.sexText }}</p>
                  <p class="info-text"><strong>年龄：</strong>{{ currentPatient.age }}岁</p>
                  <p class="info-text"><strong>身份证：</strong>{{ currentPatient.idCardMasked || '暂无' }}</p>
                </div>
              </div>
              
              <div class="info-row">
                <div class="info-item">
                  <h4>联系方式</h4>
                  <p class="info-text">{{ currentPatient.contactInfo || '暂无联系方式' }}</p>
                </div>
                <div class="info-item">
                  <h4>现住址</h4>
                  <p class="info-text">{{ currentPatient.currentAddress || '暂无地址信息' }}</p>
                </div>
                <div class="info-item">
                  <h4>出生日期</h4>
                  <p class="info-text">{{ formatBirthDate(currentPatient.dateOfBirth) }}</p>
                </div>
              </div>
              
              <div class="info-row">
                <div class="info-item">
                  <h4>传染病史</h4>
                  <p class="info-text">{{ currentPatient.infectiousDiseaseHistory || '无' }}</p>
                </div>
                <div class="info-item">
                  <h4>遗传病信息</h4>
                  <p class="info-text">{{ currentPatient.geneticDiseaseInfo || '无' }}</p>
                </div>
                <div class="info-item">
                  <h4></h4>
                  <p class="info-text"></p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 就诊历史和健康报告 -->
      <div class="bottom-section">
        <!-- 就诊历史 -->
        <div class="visit-history-card" v-loading="visitHistoryLoading">
          <h3>就诊历史</h3>
          <div class="table-header">
            <span>就诊时间</span>
            <span>接诊医生</span>
            <span>诊断结果</span>
            <span>治疗方案</span>
            <span>操作</span>
          </div>
          <div class="table-content">
            <div v-if="visitHistory.length === 0 && !visitHistoryLoading" class="empty-state">
              <p>暂无就诊记录</p>
            </div>
            <div v-for="(visit, index) in visitHistory" :key="visit.id || index" class="table-row">
              <span class="visit-date">{{ visit.date }}</span>
              <span class="doctor-name">{{ visit.doctor }}</span>
              <span class="treatment">{{ visit.treatment }}</span>
              <span class="plan">{{ visit.plan }}</span>
              <div class="actions">
                <el-button type="primary" size="small" circle @click="editVisit(visit)" title="编辑">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="info" size="small" circle @click="viewVisitDetail(visit)" title="查看详情">
                  <el-icon><User /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 健康报告 -->
        <div class="health-report-card">
          <h3>健康报告</h3>
          <div class="health-metrics">
            <div class="metric-item" v-for="metric in healthMetrics" :key="metric.name">
              <div class="metric-header">
                <span class="metric-name">{{ metric.name }}</span>
                <span class="metric-value">{{ metric.value }}</span>
              </div>
              <div class="progress-bar">
                <div class="progress-background"></div>
                <div 
                  class="progress-fill" 
                  :style="{ width: metric.percentage + '%', backgroundColor: metric.color }"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>



    <!-- 患者列表对话框 -->
    <el-dialog v-model="showPatientDialog" title="患者列表" width="90%" :before-close="closePatientDialog">
      <div style="margin-bottom: 16px;">
        <el-input
          v-model="patientSearchKeyword"
          placeholder="搜索患者姓名或身份证号"
          style="width: 300px; margin-right: 10px;"
          clearable
        />
        <el-button type="primary" @click="handlePatientSearch">搜索</el-button>
        <el-button @click="resetPatientSearch">重置</el-button>
      </div>
      <el-table 
        :data="filteredPatientList" 
        style="width: 100%;" 
        v-loading="patientListLoading"
        element-loading-text="正在加载患者数据..."
      >
        <el-table-column prop="name" label="患者姓名" width="120" />
        <el-table-column label="性别" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.sex ? 'success' : 'info'">
              {{ scope.row.sexText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="年龄" width="80">
          <template #default="scope">
            {{ scope.row.age }}岁
          </template>
        </el-table-column>
        <el-table-column prop="contactInfo" label="联系方式" width="150" />
        <el-table-column label="身份证号" width="200">
          <template #default="scope">
            <span>{{ scope.row.idCardMasked }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出生日期" width="120">
          <template #default="scope">
            {{ formatBirthDate(scope.row.dateOfBirth) }}
          </template>
        </el-table-column>
        <el-table-column prop="currentAddress" label="现住址" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="selectPatient(scope.row)">选择</el-button>
            <el-button size="small" type="primary" @click="editPatientInList(scope.row)">编辑</el-button>
            <el-button size="small" type="info" @click="viewPatientDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="searchFilteredPatientList.length > patientListPageSize"
        :current-page="patientListCurrentPage"
        :page-size="patientListPageSize"
        :total="searchFilteredPatientList.length"
        @current-change="handlePatientListPageChange"
        layout="total, prev, pager, next"
        style="margin-top: 20px; text-align: right;"
      />
    </el-dialog>

    <!-- 患者详情对话框 -->
    <el-dialog v-model="patientDetailDialogVisible" title="患者详细信息" width="800px">
      <el-descriptions :column="2" border v-if="selectedPatientDetail">
        <el-descriptions-item label="患者姓名">{{ selectedPatientDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ selectedPatientDetail.sexText }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ selectedPatientDetail.age }}岁</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ formatBirthDate(selectedPatientDetail.dateOfBirth) }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ selectedPatientDetail.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ selectedPatientDetail.idCard }}</el-descriptions-item>
        <el-descriptions-item label="现住址" :span="2">{{ selectedPatientDetail.currentAddress }}</el-descriptions-item>
        <el-descriptions-item label="传染病史" :span="2">
          {{ selectedPatientDetail.infectiousDiseaseHistory || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="遗传病信息" :span="2">
          {{ selectedPatientDetail.geneticDiseaseInfo || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ selectedPatientDetail.createPeople }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(selectedPatientDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ selectedPatientDetail.updatePeople || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(selectedPatientDetail.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="patientDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增患者对话框 -->
    <el-dialog 
      v-model="addPatientDialogVisible" 
      title="新增患者" 
      width="600px" 
      :before-close="handleCloseAddPatientDialog"
    >
      <el-form
        :model="addPatientForm"
        :rules="patientFormRules"
        ref="addPatientFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者姓名" prop="name">
              <el-input 
                v-model="addPatientForm.name" 
                placeholder="请输入患者姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="addPatientForm.sex">
                <el-radio :label="true">男</el-radio>
                <el-radio :label="false">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="dateOfBirth">
              <el-date-picker
                v-model="addPatientForm.dateOfBirth"
                type="date"
                placeholder="请选择出生日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input 
                v-model="addPatientForm.contactInfo" 
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="身份证号" prop="idCard">
          <el-input 
            v-model="addPatientForm.idCard" 
            placeholder="请输入身份证号码"
            clearable
          />
        </el-form-item>

        <el-form-item label="现住址" prop="currentAddress">
          <el-input 
            v-model="addPatientForm.currentAddress" 
            placeholder="请输入现住址"
            clearable
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="传染病史">
              <el-input 
                v-model="addPatientForm.infectiousDiseaseHistory" 
                placeholder="请输入传染病史，无则填写'无'"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="遗传病信息">
              <el-input 
                v-model="addPatientForm.geneticDiseaseInfo" 
                placeholder="请输入遗传病信息，无则填写'无'"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddPatientDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitAddPatient"
            :loading="addPatientLoading"
          >
            {{ addPatientLoading ? '创建中...' : '确定创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑患者对话框 -->
    <el-dialog 
      v-model="editPatientDialogVisible" 
      title="编辑患者信息" 
      width="600px" 
      :before-close="handleCloseEditPatientDialog"
    >
      <el-form
        :model="editPatientForm"
        :rules="patientFormRules"
        ref="editPatientFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者姓名" prop="name">
              <el-input 
                v-model="editPatientForm.name" 
                placeholder="请输入患者姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="editPatientForm.sex">
                <el-radio :label="true">男</el-radio>
                <el-radio :label="false">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="dateOfBirth">
              <el-date-picker
                v-model="editPatientForm.dateOfBirth"
                type="date"
                placeholder="请选择出生日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input 
                v-model="editPatientForm.contactInfo" 
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="身份证号" prop="idCard">
          <el-input 
            v-model="editPatientForm.idCard" 
            placeholder="请输入身份证号码"
            clearable
          />
        </el-form-item>

        <el-form-item label="现住址" prop="currentAddress">
          <el-input 
            v-model="editPatientForm.currentAddress" 
            placeholder="请输入现住址"
            clearable
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="传染病史">
              <el-input 
                v-model="editPatientForm.infectiousDiseaseHistory" 
                placeholder="请输入传染病史，无则填写'无'"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="遗传病信息">
              <el-input 
                v-model="editPatientForm.geneticDiseaseInfo" 
                placeholder="请输入遗传病信息，无则填写'无'"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseEditPatientDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitEditPatient"
            :loading="editPatientLoading"
          >
            {{ editPatientLoading ? '更新中...' : '确定更新' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, Bell, Edit, Delete
} from '@element-plus/icons-vue'
import { getPatientByAccount, getRecentVisitRecords, getPatientListByAccount } from '@/http/axiosRead'
import { addPatient, updatePatient } from '@/http/axiosWrtie'

// 响应式数据
const showPatientDialog = ref(false)
const loading = ref(false)
const currentPatient = reactive({
  id: 0,
  accountId: 0,
  name: '加载中...',
  sex: true,
  sexText: '男',
  dateOfBirth: '',
  age: 0,
  contactInfo: '',
  idCard: '',
  idCardMasked: '',
  currentAddress: '',
  infectiousDiseaseHistory: '',
  geneticDiseaseInfo: '',
  avatar: ''
})

const visitHistory = ref([])
const visitHistoryLoading = ref(false)

// 新增患者相关状态
const addPatientDialogVisible = ref(false)
const addPatientLoading = ref(false)
const addPatientFormRef = ref()

// 编辑患者相关状态
const editPatientDialogVisible = ref(false)
const editPatientLoading = ref(false)
const editPatientFormRef = ref()

// 患者详情对话框相关状态
const patientDetailDialogVisible = ref(false)
const selectedPatientDetail = ref(null)

// 新增患者表单数据
const addPatientForm = reactive({
  name: '',
  sex: true,
  dateOfBirth: '',
  contactInfo: '',
  idCard: '',
  currentAddress: '',
  infectiousDiseaseHistory: '无',
  geneticDiseaseInfo: '无'
})

// 编辑患者表单数据
const editPatientForm = reactive({
  id: 0,
  accountId: 0,
  name: '',
  sex: true,
  dateOfBirth: '',
  contactInfo: '',
  idCard: '',
  currentAddress: '',
  infectiousDiseaseHistory: '无',
  geneticDiseaseInfo: '无'
})

// 患者表单验证规则（新增和编辑共用）
const patientFormRules = reactive({
  name: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符之间', trigger: 'blur' }
  ],
  dateOfBirth: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  currentAddress: [
    { required: true, message: '请输入现住址', trigger: 'blur' }
  ]
})

const healthMetrics = ref([
  {
    name: '心率',
    value: '93',
    percentage: 75,
    color: '#CA79C6'
  },
  {
    name: '血压',
    value: '89',
    percentage: 70,
    color: '#79CFA6'
  },
  {
    name: '血糖',
    value: '60',
    percentage: 60,
    color: '#77BEEB'
  },
  {
    name: '血红蛋白',
    value: '80%',
    percentage: 80,
    color: '#FF706F'
  }
])

// 患者列表相关状态
const patientList = ref([])
const patientListLoading = ref(false)
const patientSearchKeyword = ref('')
const patientListCurrentPage = ref(1)
const patientListPageSize = ref(10)

// 搜索过滤后的患者列表
const searchFilteredPatientList = computed(() => {
  let filtered = patientList.value
  
  // 搜索过滤
  if (patientSearchKeyword.value) {
    const keyword = patientSearchKeyword.value.toLowerCase()
    filtered = filtered.filter(patient => 
      patient.name.toLowerCase().includes(keyword) ||
      patient.idCard.includes(keyword) ||
      patient.idCardMasked.includes(keyword) ||
      patient.contactInfo.includes(keyword)
    )
  }
  
  return filtered
})

// 分页后的患者列表
const filteredPatientList = computed(() => {
  const filtered = searchFilteredPatientList.value
  const start = (patientListCurrentPage.value - 1) * patientListPageSize.value
  const end = start + patientListPageSize.value
  return filtered.slice(start, end)
})

// 获取患者列表数据
const fetchPatientList = async () => {
  patientListLoading.value = true
  try {
    // 从localStorage获取当前登录用户的accountId
    const userInfo = localStorage.getItem('Uid')
    let accountId = null
    
    if (userInfo) {
      try {
        const user = JSON.parse(userInfo)
        accountId = user.accountId || user.id
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
    
    // 如果没有找到accountId，尝试其他方式获取
    if (!accountId) {
      accountId = localStorage.getItem('Uid') || localStorage.getItem('Uid')
    }
    
    if (!accountId) {
      ElMessage.warning('未找到登录用户信息，请重新登录')
      return
    }
    
    console.log('调用患者列表接口，accountId:', accountId)
    const res = await getPatientListByAccount(Number(accountId))
    if (res.data.code === 200) {
      patientList.value = res.data.data || []
      ElMessage.success(`成功加载${patientList.value.length}条患者数据`)
    } else {
      ElMessage.error(res.data.msg || '获取患者列表失败')
      patientList.value = []
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    patientList.value = []
  } finally {
    patientListLoading.value = false
  }
}

// 方法
const showPatientList = async () => {
  showPatientDialog.value = true
  // 显示对话框时立即获取患者列表
  if (patientList.value.length === 0) {
    await fetchPatientList()
  }
}

// 处理患者搜索
const handlePatientSearch = () => {
  patientListCurrentPage.value = 1 // 重置到第一页
}

// 重置患者搜索
const resetPatientSearch = () => {
  patientSearchKeyword.value = ''
  patientListCurrentPage.value = 1
}

// 分页处理
const handlePatientListPageChange = (page) => {
  patientListCurrentPage.value = page
}

const closePatientDialog = () => {
  showPatientDialog.value = false
}

// 显示新增患者弹窗
const handleAddPatient = () => {
  addPatientDialogVisible.value = true
  resetAddPatientForm()
}

// 重置新增患者表单
const resetAddPatientForm = () => {
  Object.assign(addPatientForm, {
    name: '',
    sex: true,
    dateOfBirth: '',
    contactInfo: '',
    idCard: '',
    currentAddress: '',
    infectiousDiseaseHistory: '无',
    geneticDiseaseInfo: '无'
  })
  addPatientFormRef.value?.clearValidate()
}

// 关闭新增患者弹窗
const handleCloseAddPatientDialog = () => {
  addPatientDialogVisible.value = false
  resetAddPatientForm()
}

// 提交新增患者
const handleSubmitAddPatient = async () => {
  if (!addPatientFormRef.value) return
  
  try {
    const valid = await addPatientFormRef.value.validate()
    if (!valid) return
    
    addPatientLoading.value = true
    
    // 获取当前登录用户信息
    const accountId = localStorage.getItem('accountId') || localStorage.getItem('userId') || '1'
    const createPeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    
    // 准备提交数据
    const submitData = {
      accountId: Number(accountId),
      name: addPatientForm.name,
      sex: addPatientForm.sex,
      dateOfBirth: new Date(addPatientForm.dateOfBirth).toISOString(),
      contactInfo: addPatientForm.contactInfo,
      idCard: addPatientForm.idCard,
      currentAddress: addPatientForm.currentAddress,
      infectiousDiseaseHistory: addPatientForm.infectiousDiseaseHistory,
      geneticDiseaseInfo: addPatientForm.geneticDiseaseInfo,
      createPeople: createPeople
    }
    
    const response = await addPatient(submitData)
    
    if (response.data && response.data.id) {
      ElMessage.success(response.data.message || '患者创建成功')
      addPatientDialogVisible.value = false
      resetAddPatientForm()
      
      // 刷新当前患者信息（如果创建的患者属于当前账户）
      if (Number(accountId) === Number(submitData.accountId)) {
        getPatientInfo()
      }
      
      // 如果患者列表已加载，也刷新患者列表
      if (patientList.value.length > 0) {
        fetchPatientList()
      }
    } else {
      ElMessage.error('患者创建失败')
    }
  } catch (error) {
    console.error('创建患者失败:', error)
    ElMessage.error('创建患者失败，请重试')
  } finally {
    addPatientLoading.value = false
  }
}

// 显示编辑患者弹窗
const handleEditPatient = () => {
  if (!currentPatient.id) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 预填充编辑表单
  Object.assign(editPatientForm, {
    id: currentPatient.id,
    accountId: currentPatient.accountId,
    name: currentPatient.name,
    sex: currentPatient.sex,
    dateOfBirth: formatDateForInput(currentPatient.dateOfBirth),
    contactInfo: currentPatient.contactInfo || '',
    idCard: currentPatient.idCard || '',
    currentAddress: currentPatient.currentAddress || '',
    infectiousDiseaseHistory: currentPatient.infectiousDiseaseHistory || '无',
    geneticDiseaseInfo: currentPatient.geneticDiseaseInfo || '无'
  })
  
  editPatientDialogVisible.value = true
}

// 格式化日期为输入框格式
const formatDateForInput = (dateStr) => {
  if (!dateStr) return ''
  try {
    return new Date(dateStr).toISOString().split('T')[0]
  } catch (error) {
    return ''
  }
}

// 关闭编辑患者弹窗
const handleCloseEditPatientDialog = () => {
  editPatientDialogVisible.value = false
  resetEditPatientForm()
}

// 重置编辑患者表单
const resetEditPatientForm = () => {
  Object.assign(editPatientForm, {
    id: 0,
    accountId: 0,
    name: '',
    sex: true,
    dateOfBirth: '',
    contactInfo: '',
    idCard: '',
    currentAddress: '',
    infectiousDiseaseHistory: '无',
    geneticDiseaseInfo: '无'
  })
  editPatientFormRef.value?.clearValidate()
}

// 提交编辑患者
const handleSubmitEditPatient = async () => {
  if (!editPatientFormRef.value) return
  
  try {
    const valid = await editPatientFormRef.value.validate()
    if (!valid) return
    
    editPatientLoading.value = true
    
    // 获取当前登录用户信息
    const updatePeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    
    // 准备提交数据
    const submitData = {
      id: editPatientForm.id,
      accountId: editPatientForm.accountId,
      name: editPatientForm.name,
      sex: editPatientForm.sex,
      dateOfBirth: new Date(editPatientForm.dateOfBirth).toISOString(),
      contactInfo: editPatientForm.contactInfo,
      idCard: editPatientForm.idCard,
      currentAddress: editPatientForm.currentAddress,
      infectiousDiseaseHistory: editPatientForm.infectiousDiseaseHistory,
      geneticDiseaseInfo: editPatientForm.geneticDiseaseInfo,
      updatePeople: updatePeople
    }
    
    const response = await updatePatient(submitData)
    
    if (response.data && response.data.message) {
      ElMessage.success(response.data.message || '患者信息更新成功')
      editPatientDialogVisible.value = false
      resetEditPatientForm()
      
      // 刷新当前患者信息
      getPatientInfo()
      
      // 如果患者列表已加载，也刷新患者列表
      if (patientList.value.length > 0) {
        fetchPatientList()
      }
    } else {
      ElMessage.error('患者信息更新失败')
    }
  } catch (error) {
    console.error('更新患者信息失败:', error)
    ElMessage.error('更新患者信息失败，请重试')
  } finally {
    editPatientLoading.value = false
  }
}

// 选择患者
const selectPatient = (patient) => {
  // 将患者数据映射到currentPatient的结构
  Object.assign(currentPatient, {
    id: patient.id,
    accountId: patient.accountId,
    name: patient.name,
    sex: patient.sex,
    sexText: patient.sexText,
    dateOfBirth: patient.dateOfBirth,
    age: patient.age,
    contactInfo: patient.contactInfo,
    idCard: patient.idCard,
    idCardMasked: patient.idCardMasked,
    currentAddress: patient.currentAddress,
    infectiousDiseaseHistory: patient.infectiousDiseaseHistory,
    geneticDiseaseInfo: patient.geneticDiseaseInfo,
    avatar: ''
  })
  showPatientDialog.value = false
  ElMessage.success(`已选择患者：${patient.name}`)
}

// 查看患者详情
const viewPatientDetail = (patient) => {
  selectedPatientDetail.value = patient
  patientDetailDialogVisible.value = true
}

// 在患者列表中编辑患者
const editPatientInList = (patient) => {
  // 预填充编辑表单
  Object.assign(editPatientForm, {
    id: patient.id,
    accountId: patient.accountId,
    name: patient.name,
    sex: patient.sex,
    dateOfBirth: formatDateForInput(patient.dateOfBirth),
    contactInfo: patient.contactInfo || '',
    idCard: patient.idCard || '',
    currentAddress: patient.currentAddress || '',
    infectiousDiseaseHistory: patient.infectiousDiseaseHistory || '无',
    geneticDiseaseInfo: patient.geneticDiseaseInfo || '无'
  })
  
  editPatientDialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch (error) {
    return '-'
  }
}

const editVisit = (visit) => {
  ElMessage.info(`编辑就诊记录：${visit.treatment}`)
}

const viewVisitDetail = (visit) => {
  ElMessageBox.alert(
    `
    <div style="text-align: left; line-height: 1.6;">
      <p><strong>就诊时间：</strong>${visit.date}</p>
      <p><strong>接诊医生：</strong>${visit.doctor}</p>
      <p><strong>诊断结果：</strong>${visit.treatment}</p>
      <p><strong>治疗方案：</strong>${visit.plan}</p>
      ${visit.location ? `<p><strong>就诊地点：</strong>${visit.location}</p>` : ''}
    </div>
    `,
    '就诊记录详情',
    {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true
    }
  )
}

const deleteVisit = (visit) => {
  ElMessageBox.confirm(
    `确定要删除这条就诊记录吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const index = visitHistory.value.findIndex(v => v.id === visit.id)
    if (index > -1) {
      visitHistory.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}



// 格式化出生日期
const formatBirthDate = (dateStr) => {
  if (!dateStr) return '暂无'
  
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return '暂无'
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    return '暂无'
  }
}

// 获取患者信息
const getPatientInfo = async () => {
  loading.value = true
  try {
    // 从localStorage获取登录用户的ID
    const accountId = localStorage.getItem('Uid') || localStorage.getItem('Uid') || '1'
    
    const response = await getPatientByAccount(Number(accountId))
    
    if (response.data && response.data.code === 200 && response.data.data) {
      const data = response.data.data
      
      // 更新患者信息
      Object.assign(currentPatient, {
        id: data.id,
        accountId: data.accountId,
        name: data.name,
        sex: data.sex,
        sexText: data.sexText,
        dateOfBirth: data.dateOfBirth,
        age: data.age,
        contactInfo: data.contactInfo,
        idCard: data.idCard,
        idCardMasked: data.idCardMasked,
        currentAddress: data.currentAddress,
        infectiousDiseaseHistory: data.infectiousDiseaseHistory,
        geneticDiseaseInfo: data.geneticDiseaseInfo,
        avatar: data.avatar || ''
      })
      
      console.log('患者信息加载成功:', data)
      
      // 获取患者信息成功后，获取就诊记录
      getVisitHistory(data.id)
    } else {
      // 使用模拟数据作为fallback
      console.warn('患者信息获取失败，使用模拟数据')
      Object.assign(currentPatient, {
        id: 1,
        accountId: 1,
        name: '章哈哈',
        sex: true,
        sexText: '男',
        dateOfBirth: '2000-07-01T02:00:24.267',
        age: 25,
        contactInfo: '17410540900',
        idCard: '612248271231799',
        idCardMasked: '612248********1799',
        currentAddress: '江苏省南京市',
        infectiousDiseaseHistory: '无',
        geneticDiseaseInfo: '无',
        avatar: ''
      })
      
      // 使用模拟数据时也获取就诊记录
      getVisitHistory(1)
    }
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败')
    
    
    
  } finally {
    loading.value = false
  }
}

// 获取就诊记录
const getVisitHistory = async (patientId) => {
  if (!patientId) return
  
  visitHistoryLoading.value = true
  try {
    const response = await getRecentVisitRecords(patientId)
    
    if (response.data && response.data.code === 200 && response.data.data) {
      // 转换数据格式以匹配现有表格结构
      visitHistory.value = response.data.data.map(item => ({
        id: item.id,
        date: item.visitTimeText || item.visitTime,
        doctor: item.createPeople || '医生',
        treatment: item.diagnosisResult || '诊断',
        plan: item.treatmentPlan || '治疗方案',
        location: item.visitLocation || '就诊地点',
        visitTypeId: item.visitTypeId
      }))
      
      console.log('就诊记录加载成功:', response.data.data)
    } else {
      // 使用模拟数据
      console.warn('就诊记录获取失败，使用模拟数据')
      visitHistory.value = [
        {
          id: 1,
          date: '2025-07-29 10:32',
          doctor: '梅雨',
          treatment: '胃溃疡',
          plan: '保守治疗',
          location: '北京市朝阳区朝阳医院'
        },
        {
          id: 2,
          date: '2025-06-03 10:32',
          doctor: '莘花',
          treatment: '手臂擦伤',
          plan: '涂抹药膏',
          location: '北京市朝阳区朝阳医院'
        }
      ]
    }
  } catch (error) {
    console.error('获取就诊记录失败:', error)
    ElMessage.error('获取就诊记录失败')
    
    // 错误时使用模拟数据
    visitHistory.value = [
      {
        id: 1,
        date: '2025-07-29 10:32',
        doctor: '梅雨',
        treatment: '胃溃疡',
        plan: '保守治疗',
        location: '北京市朝阳区朝阳医院'
      },
      {
        id: 2,
        date: '2025-06-03 10:32',
        doctor: '莘花',
        treatment: '手臂擦伤',
        plan: '涂抹药膏',
        location: '北京市朝阳区朝阳医院'
      }
    ]
  } finally {
    visitHistoryLoading.value = false
  }
}

onMounted(() => {
  // 初始化时获取患者数据
  getPatientInfo()
})
</script>

<style scoped>
/* 引入Kanit字体 */
@import url('https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600&display=swap');

.patient-dashboard {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #D8D2FC 0%, #FDE2E0 28.35%, #E6E4EA 58.79%, #E0E9F4 100%);
  font-family: 'Kanit', 'Microsoft YaHei', sans-serif;
}

.main-content {
  flex: 1;
  padding: 20px;
}

.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.profile-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  background: white;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.page-title {
  font-size: 42px;
  font-weight: 500;
  color: #271E4A;
  margin: 0;
}

.nav-actions {
  display: flex;
  gap: 10px;
}

.nav-button {
  width: 48px;
  height: 48px;
  border-radius: 20px;
  background: white;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  border: none;
}

.patient-info-card {
  background: white;
  border-radius: 47px;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  padding: 40px;
  margin-bottom: 30px;
}

.patient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.patient-header h3 {
  font-size: 24px;
  font-weight: 500;
  color: #271E4A;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.action-buttons .el-button {
  border-radius: 5px;
  font-weight: 600;
  font-size: 14px;
}

.patient-details {
  display: flex;
  gap: 40px;
}

.patient-avatar-section {
  flex-shrink: 0;
}

.avatar-container {
  width: 225px;
  height: 225px;
  border-radius: 47px;
  overflow: hidden;
  background: #f0f0f0;
  border: 2px solid #000;
}

.avatar-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.patient-info-section {
  flex: 1;
}

.info-group {
  margin-bottom: 30px;
}

.info-group h4,
.info-item h4 {
  font-size: 18px;
  font-weight: 500;
  color: #271E4A;
  margin: 0 0 10px 0;
}

.info-text {
  font-size: 16px;
  font-weight: 300;
  color: rgba(39, 30, 74, 0.8);
  margin: 0;
  line-height: 1.5;
}

.info-row {
  display: flex;
  gap: 40px;
}

.info-item {
  flex: 1;
}

.basic-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-top: 10px;
}

.basic-info .info-text {
  margin: 5px 0;
}

/* 就诊历史表格优化 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: rgba(39, 30, 74, 0.6);
}

.empty-state p {
  margin: 0;
  font-size: 16px;
}

.table-row .visit-date {
  font-weight: 500;
  color: #271E4A;
}

.table-row .doctor-name {
  color: #4A90E2;
  font-weight: 500;
}

.table-row .treatment {
  color: #E74C3C;
  font-weight: 500;
}

.table-row .plan {
  color: #27AE60;
  font-weight: 500;
}

/* 基本信息头部布局 */
.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.info-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.info-header .el-button {
  font-size: 12px;
  padding: 6px 12px;
}

/* 新增患者对话框样式 */
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 表单布局优化 */
.el-form .el-row {
  margin-bottom: 0;
}

.el-form .el-form-item {
  margin-bottom: 18px;
}

.el-radio-group .el-radio {
  margin-right: 20px;
}

.bottom-section {
  display: flex;
  gap: 30px;
}

.visit-history-card,
.health-report-card {
  background: white;
  border-radius: 47px;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  padding: 30px;
}

.visit-history-card {
  flex: 1;
}

.health-report-card {
  width: 400px;
}

.visit-history-card h3,
.health-report-card h3 {
  font-size: 24px;
  font-weight: 500;
  color: #271E4A;
  margin: 0 0 20px 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  padding: 15px 20px;
  background: #EDF4FC;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 300;
  color: #271E4A;
  opacity: 0.9;
  margin-bottom: 10px;
}

.table-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.table-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(185, 178, 226, 0.64);
  font-size: 14px;
  color: #271E4A;
}

.table-row:not(:last-child) {
  border-bottom: 1px solid #E0E9F4;
}

.cost {
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 10px;
}

.actions .el-button {
  width: 30px;
  height: 30px;
}

.health-metrics {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.metric-item {
  margin-bottom: 20px;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.metric-name {
  font-size: 18px;
  font-weight: 500;
  color: #271E4A;
}

.metric-value {
  font-size: 16px;
  font-weight: 400;
  color: rgba(39, 30, 74, 0.8);
}

.progress-bar {
  position: relative;
  height: 12px;
  border-radius: 6px;
  overflow: hidden;
}

.progress-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #E0E9F4;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  border-radius: 6px;
  transition: width 0.3s ease;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 15px;
  }
  
  .patient-details {
    flex-direction: column;
    gap: 20px;
  }
  
  .bottom-section {
    flex-direction: column;
  }
  
  .health-report-card {
    width: 100%;
  }
  
  .info-row {
    flex-direction: column;
    gap: 20px;
  }
}
</style>